package com.example.demoback.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.demoback.entity.People;
import com.example.demoback.service.IPeopleService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtils {

    private static IPeopleService staticPeopleService;

    @Resource
    private IPeopleService iPeopleService;

    @PostConstruct
    public void setUserService() {
        staticPeopleService = iPeopleService; //只有静态方法能引用下面的静态对象，静态接口staticUserService下的方法为静态
    }


    public static String genToken(String userId, String sign){
        String token = JWT.create().withAudience(userId) // 将 user id 保存到 token 里面 , 作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2)) //2小时后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
        return token;
    }


    public static People getCurrentUser() {
        try {
            //获取当前请求的request
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");//获取token
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);//获取token中的id
                return staticPeopleService.getById(Integer.valueOf(userId));//根据id查询user对象
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
